package com.flower.ApiGateway.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flower.ApiGateway.constant.SysConstant;
import com.flower.ApiGateway.dao.PlatformDao;
import com.flower.ApiGateway.dao.UserDao;
import com.flower.ApiGateway.entity.HttpResponseBean;
import com.flower.ApiGateway.entity.LoginEntity;
import com.flower.ApiGateway.entity.OpenPlatformEntity;
import com.flower.ApiGateway.entity.PlatformEntity;
import com.flower.ApiGateway.entity.UserEntity;
import com.flower.ApiGateway.service.UserService;
import com.flower.ApiGateway.untils.JwtTokenUtil;
import com.flower.ApiGateway.untils.MD5Util;
import com.flower.ApiGateway.untils.WechatUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Value("${jwt.security.user}")
    private String security_user;

    @Value("${jwt.security.pass}")
    private String security_pass;
    
    @Value("${wechat.appid}")
    private String wechat_app_appid;
    
    @Value("${wechat.secret}")
    private String wechat_app_secret;

    @Value("${wechat.grant_type}")
    private String wechat_app_grant_type;


    private static long BanTime =60*60*1000;
   
    
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private PlatformDao platformDao;
    
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
    
    @Override
    public HttpResponseBean login(LoginEntity entity) {
    	//处理明文密码验证
    	String pass =MD5Util.toMD52(MD5Util.md5Encode(entity.getSecurity_pass())) ;
    	UserEntity user = userDao.findByUsername(entity.getSecurity_user());
    	if(user != null) {
    		if(user.getLoginstate().equals("1")) {
    			return new HttpResponseBean(SysConstant.errLogin_code, SysConstant.errLogin_message);
    		}
    		if(user.getDelflag().equals("1")) {
    			return new HttpResponseBean(SysConstant.errLogin_code, SysConstant.not_account);
    		}
    		//密码匹配 重置冻结次数,更新上次登陆时间
    		if(pass.equals(user.getPasswd())) {
    			user.setLoginerr(0);
    			user.setLasttime(new Date());
    			userDao.save(user);
    			return new HttpResponseBean(SysConstant.login_succ_code, jwtTokenUtil.generateToken(entity.getSecurity_user()));
    		}
    		if(!pass.equals(user.getPasswd())) {
    			if(user.getLoginerr() == 4) {
    				Long ban= new Date().getTime()+BanTime;
    				user.setLoginerr(5);
    				user.setLoginstate("1");
    				user.setBantime(new Date(ban));
    				userDao.save(user);
    				return new HttpResponseBean(SysConstant.errLogin_code, SysConstant.errLogin_message);
    			}else {
    				int errorLogin = user.getLoginerr();
    				user.setLoginerr(++errorLogin);
    				userDao.save(user);
    				return new HttpResponseBean(SysConstant.errLogin_code, "密码错误请重试，重试剩余"+(5-errorLogin+1)+"次");
    			}
    		}
    	}else{
    		return new HttpResponseBean(SysConstant.sysError_code, SysConstant.not_account);
    	}

    	return new HttpResponseBean(SysConstant.sysError_code, SysConstant.sysError_msg);
    }

	@Override
	public HttpResponseBean saveUser(UserEntity entity) {
		UserEntity user = userDao.findByUsername(entity.getUsername());
		if(user != null) {
			return new HttpResponseBean(SysConstant.succ_code,"添加失败，用户名已存在");
		}
		String pass =MD5Util.toMD52(MD5Util.md5Encode(entity.getPasswd()));
		entity.setPasswd(pass);
		entity.setNickname("用户名");
		entity.setIntroduce("该用户还未编写个人介绍");
		entity.setAge(18);
		entity.setAutograph("该用户未设置个人签名");
		entity.setGender("男");
		entity.setDelflag("0");
		entity.setLoginstate("0");
		entity.setLoginaddr("0.0.0.0");
		entity.setLoginerr(0);
		entity.setBantime(null);
		userDao.save(entity);
		return new HttpResponseBean(SysConstant.succ_code,"用户保存成功");
	}

	@Override
	public HttpResponseBean OpenPlatformlogin(OpenPlatformEntity entity) {
		//登录请求开始
		if(entity.getPlatform() != null && !entity.getPlatform() .equals("")) {
			switch (entity.getPlatform()) {
			case "wechat_app":
				//解析code
				String openUser ="https://api.weixin.qq.com/sns/jscode2session?appid="+wechat_app_appid+"&secret="+wechat_app_secret+"&js_code="+entity.getOpenCode()+"&grant_type="+wechat_app_grant_type;
				String login_json = WechatUtil.httpsRequest(openUser, "GET", null);
				JSONObject login_res = (JSONObject) JSON.parse(login_json);
				if(login_res.get("errcode") != null && login_res.get("errcode").equals("40013")) {
					return new HttpResponseBean(SysConstant.sysError_code, SysConstant.platform_appid_err);
				}
				
				if(login_res.get("openid") != null) {
					PlatformEntity platform = platformDao.findByOpenid(login_res.get("openid").toString());
				
				}
				
				break;

			default:
				return new HttpResponseBean(SysConstant.sysError_code, SysConstant.not_match_platform);
			}
		}
		return new HttpResponseBean(SysConstant.sysError_code, SysConstant.sysError_msg);
	}
}
